"""
第三阶段主处理器 - 多代理审查核心的统一接口
"""

import json
import time
from pathlib import Path
from typing import Dict, List, Any, Optional
from loguru import logger

from .config import Stage3Config
from .orchestrator import MasterOrchestrator
from .retriever import Retriever


class Stage3Processor:
    """第三阶段主处理器类"""
    
    def __init__(self, config_path: str = None, **config_kwargs):
        """
        初始化第三阶段处理器
        
        Args:
            config_path: 配置文件路径
            **config_kwargs: 配置参数
        """
        self.config = self._load_config(config_path, **config_kwargs)
        self.orchestrator = MasterOrchestrator(self.config)
        self.retriever = Retriever(self.config)
        
        logger.info("AIDA框架第三阶段处理器初始化完成")
    
    def _load_config(self, config_path: str = None, **config_kwargs) -> Stage3Config:
        """加载配置"""
        try:
            # 如果直接传入了config对象，直接返回
            if 'config' in config_kwargs and isinstance(config_kwargs['config'], Stage3Config):
                return config_kwargs['config']
            
            if config_path and Path(config_path).exists():
                # 从文件加载配置
                with open(config_path, 'r', encoding='utf-8') as f:
                    config_data = json.load(f)
                # 移除config参数，避免冲突
                filtered_kwargs = {k: v for k, v in config_kwargs.items() if k != 'config'}
                config_data.update(filtered_kwargs)
                return Stage3Config.from_dict(config_data)
            else:
                # 使用默认配置和传入参数
                # 移除config参数，避免冲突
                filtered_kwargs = {k: v for k, v in config_kwargs.items() if k != 'config'}
                if filtered_kwargs:
                    return Stage3Config.from_dict(filtered_kwargs)
                else:
                    return Stage3Config()
                
        except Exception as e:
            logger.warning(f"配置加载失败，使用默认配置: {e}")
            # 如果有config对象，尝试使用它
            if 'config' in config_kwargs and isinstance(config_kwargs['config'], Stage3Config):
                return config_kwargs['config']
            # 否则创建默认配置
            return Stage3Config()
    
    def process(self, session_id: str = None, save_results: bool = True, 
                output_path: str = None) -> Dict[str, Any]:
        """
        执行第三阶段多代理审查
        
        Args:
            session_id: 会话ID，如果为None则使用最新会话
            save_results: 是否保存结果
            output_path: 结果保存路径
            
        Returns:
            审查结果字典
        """
        start_time = time.time()
        
        try:
            logger.info("开始执行AIDA框架第三阶段多代理审查")
            
            # 执行多代理审查
            results = self.orchestrator.process_session(session_id)
            
            if not results.get('success', False):
                logger.error(f"多代理审查失败: {results.get('error', '未知错误')}")
                return results
            
            # 添加处理器信息
            results['processor_info'] = {
                'stage': 3,
                'version': '1.0.0',
                'description': 'AIDA框架多代理审查核心',
                'total_processing_time': time.time() - start_time,
                'has_final_summary': 'final_summary' in results
            }
            
            # 记录最终总结信息
            if 'final_summary' in results:
                final_summary = results['final_summary']
                if final_summary.get('success', False):
                    logger.info("最终总结报告生成成功")
                    logger.info(f"总结了 {final_summary.get('expert_results_count', 0)} 个专家代理结果")
                else:
                    logger.warning(f"最终总结报告生成失败: {final_summary.get('error', '未知错误')}")
            
            # 保存结果
            if save_results:
                saved_path = self._save_results(results, output_path)
                results['saved_path'] = saved_path
                logger.info(f"审查结果已保存到: {saved_path}")
            
            logger.info(f"第三阶段处理完成，总耗时: {time.time() - start_time:.2f}秒")
            return results
            
        except Exception as e:
            logger.error(f"第三阶段处理失败: {e}")
            return {
                'success': False,
                'error': str(e),
                'stage': 3,
                'processing_time': time.time() - start_time
            }
    
    def _save_results(self, results: Dict[str, Any], output_path: str = None) -> str:
        """保存审查结果"""
        try:
            # 确定保存路径
            if output_path:
                save_path = Path(output_path)
            else:
                session_id = results.get('session_id', 'unknown')
                timestamp = int(time.time())
                filename = f"stage3_review_results_{session_id}_{timestamp}.json"
                save_path = Path(self.config.storage_path) / session_id / filename
            
            # 确保目录存在
            save_path.parent.mkdir(parents=True, exist_ok=True)
            
            # 保存结果
            with open(save_path, 'w', encoding='utf-8') as f:
                json.dump(results, f, ensure_ascii=False, indent=2)
            
            return str(save_path)
            
        except Exception as e:
            logger.error(f"保存结果失败: {e}")
            raise
    
    def get_session_info(self, session_id: str = None) -> Dict[str, Any]:
        """获取会话信息"""
        try:
            return self.retriever.get_session_summary(session_id)
        except Exception as e:
            logger.error(f"获取会话信息失败: {e}")
            return {'error': str(e)}
    
    def get_agent_status(self) -> Dict[str, Any]:
        """获取代理状态"""
        try:
            return self.orchestrator.get_agent_status()
        except Exception as e:
            logger.error(f"获取代理状态失败: {e}")
            return {'error': str(e)}
    
    def validate_config(self) -> Dict[str, Any]:
        """验证配置"""
        try:
            validation_result = self.config.validate()
            return {
                'valid': validation_result,
                'config_summary': {
                    'api_configured': bool(self.config.api.api_key),
                    'storage_path': self.config.storage_path,
                    'parallel_enabled': self.config.agent.enable_parallel_processing,
                    'max_agents': self.config.agent.max_parallel_agents
                }
            }
        except Exception as e:
            logger.error(f"配置验证失败: {e}")
            return {'valid': False, 'error': str(e)}
    
    def test_api_connection(self) -> Dict[str, Any]:
        """测试API连接"""
        try:
            # 测试API连接
            test_response = self.orchestrator.api_client.chat_completion(
                messages=[{"role": "user", "content": "测试连接"}],
                model=self.config.api.text_model
            )
            
            return {
                'success': True,
                'message': 'API连接正常',
                'model': self.config.api.text_model,
                'response_preview': test_response[:100] if test_response else 'Empty response'
            }
            
        except Exception as e:
            logger.error(f"API连接测试失败: {e}")
            return {
                'success': False,
                'error': str(e),
                'message': 'API连接失败'
            }
    
    def process_with_custom_agents(self, session_id: str = None, 
                                 agent_types: List[str] = None) -> Dict[str, Any]:
        """使用指定的代理类型进行处理"""
        if not agent_types:
            return self.process(session_id)
        
        try:
            # 临时修改代理配置
            original_agents = self.orchestrator.agents.copy()
            
            # 过滤代理
            filtered_agents = {
                name: agent for name, agent in original_agents.items()
                if agent.agent_type in agent_types
            }
            
            if not filtered_agents:
                return {
                    'success': False,
                    'error': f'没有找到指定类型的代理: {agent_types}'
                }
            
            # 临时替换代理
            self.orchestrator.agents = filtered_agents
            
            # 执行处理
            results = self.orchestrator.process_session(session_id)
            
            # 恢复原始代理
            self.orchestrator.agents = original_agents
            
            # 添加自定义处理信息
            results['custom_processing'] = {
                'requested_agents': agent_types,
                'used_agents': list(filtered_agents.keys()),
                'total_agents': len(filtered_agents)
            }
            
            return results
            
        except Exception as e:
            # 确保恢复原始代理
            self.orchestrator.agents = original_agents
            logger.error(f"自定义代理处理失败: {e}")
            return {
                'success': False,
                'error': str(e)
            }
    
    def get_available_sessions(self) -> List[str]:
        """获取可用的会话列表"""
        try:
            storage_path = Path(self.config.storage_path)
            if not storage_path.exists():
                return []
            
            sessions = []
            for item in storage_path.iterdir():
                if item.is_dir() and item.name.startswith('session_'):
                    sessions.append(item.name)
            
            return sorted(sessions, reverse=True)  # 最新的在前
            
        except Exception as e:
            logger.error(f"获取会话列表失败: {e}")
            return []
    
    def export_results_summary(self, results: Dict[str, Any], 
                             format_type: str = 'json') -> str:
        """导出结果摘要"""
        try:
            if format_type.lower() == 'json':
                return self._export_json_summary(results)
            elif format_type.lower() == 'markdown':
                return self._export_markdown_summary(results)
            elif format_type.lower() == 'text':
                return self._export_text_summary(results)
            else:
                raise ValueError(f"不支持的导出格式: {format_type}")
                
        except Exception as e:
            logger.error(f"导出结果摘要失败: {e}")
            return f"导出失败: {str(e)}"
    
    def _export_json_summary(self, results: Dict[str, Any]) -> str:
        """导出JSON格式摘要"""
        summary = {
            'session_id': results.get('session_id'),
            'processing_time': results.get('processing_time'),
            'success': results.get('success'),
            'statistics': results.get('aggregated_results', {}).get('statistics', {}),
            'overall_assessment': results.get('aggregated_results', {}).get('overall_assessment', {}),
            'agent_summaries': results.get('aggregated_results', {}).get('agent_summaries', {}),
            'final_summary': results.get('final_summary', {})
        }
        
        return json.dumps(summary, ensure_ascii=False, indent=2)
    
    def _export_markdown_summary(self, results: Dict[str, Any]) -> str:
        """导出Markdown格式摘要"""
        lines = [
            "# AIDA框架第三阶段审查结果摘要",
            "",
            f"**会话ID**: {results.get('session_id', 'N/A')}",
            f"**处理时间**: {results.get('processing_time', 0):.2f}秒",
            f"**处理状态**: {'成功' if results.get('success') else '失败'}",
            ""
        ]
        
        # 统计信息
        stats = results.get('aggregated_results', {}).get('statistics', {})
        if stats:
            lines.extend([
                "## 统计信息",
                "",
                f"- 总问题数: {stats.get('total_findings', 0)}",
                f"- 严重问题: {stats.get('severity_distribution', {}).get('critical', 0)}",
                f"- 重要问题: {stats.get('severity_distribution', {}).get('major', 0)}",
                f"- 轻微问题: {stats.get('severity_distribution', {}).get('minor', 0)}",
                ""
            ])
        
        # 整体评估
        assessment = results.get('aggregated_results', {}).get('overall_assessment', {})
        if assessment:
            lines.extend([
                "## 整体评估",
                "",
                f"**评分**: {assessment.get('score', 'N/A')}",
                f"**摘要**: {assessment.get('summary', 'N/A')}",
                f"**建议**: {assessment.get('recommendation', 'N/A')}",
                ""
            ])
        
        return "\n".join(lines)
    
    def _export_text_summary(self, results: Dict[str, Any]) -> str:
        """导出纯文本格式摘要"""
        lines = [
            "AIDA框架第三阶段审查结果摘要",
            "=" * 40,
            "",
            f"会话ID: {results.get('session_id', 'N/A')}",
            f"处理时间: {results.get('processing_time', 0):.2f}秒",
            f"处理状态: {'成功' if results.get('success') else '失败'}",
            ""
        ]
        
        # 统计信息
        stats = results.get('aggregated_results', {}).get('statistics', {})
        if stats:
            lines.extend([
                "统计信息:",
                f"  总问题数: {stats.get('total_findings', 0)}",
                f"  严重问题: {stats.get('severity_distribution', {}).get('critical', 0)}",
                f"  重要问题: {stats.get('severity_distribution', {}).get('major', 0)}",
                f"  轻微问题: {stats.get('severity_distribution', {}).get('minor', 0)}",
                ""
            ])
        
        # 整体评估
        assessment = results.get('aggregated_results', {}).get('overall_assessment', {})
        if assessment:
            lines.extend([
                "整体评估:",
                f"  评分: {assessment.get('score', 'N/A')}",
                f"  摘要: {assessment.get('summary', 'N/A')}",
                f"  建议: {assessment.get('recommendation', 'N/A')}",
                ""
            ])
        
        return "\n".join(lines)